package com.gitee.ywj1352.mongodb.Morph;

import com.gitee.ywj1352.mongodb.Morph.entity.Person;
import com.mongodb.MongoClient;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.Morphia;
import org.mongodb.morphia.query.UpdateOperations;

/**
 * @author wenjie.yang on 2019/6/25.
 */
public class MorphTest {
    final static Morphia morphia= new Morphia();
    public static void main(String[] args) {
//        Datastore datastore = morphia.createDatastore(new MongoClient("localhost", 27017), "testdb");
//        Query<Person> people = datastore.find(Person.class);
//        Person person1 = people.get();
//        System.out.println(person1.toString());
        delete();
    }
    public static void create(){
        Datastore datastore = morphia.createDatastore(new MongoClient("localhost", 27017), "testdb");
        Person person = new Person();
        person.setAge(10);
        person.setName("wenjie");
        person.setAddress("shanghai");
        Key<Person> key = datastore.save(person);
        System.out.println(
                key.getId()
        );
    }

    public static void update(){
        Datastore datastore = morphia.createDatastore(new MongoClient("localhost", 27017), "testdb");
        Person person = datastore.find(Person.class).get();
        //inc 是加减的原子操作 目前还存在
        //$set
        //用来指定一个键并更新键值，若键不存在并创建。
        /**
         * $unset
         * 用来删除一个键。
         * $push
         * 把value追加到field里面去，field一定要是数组类型才行，如果field不存在，会新增一个数组类型加进去。
         * $pushAll
         * 同$push,只是一次可以追加多个值到一个数组字段内
         */
        UpdateOperations<Person> ops = datastore.createUpdateOperations(Person.class).inc("age",100);
        datastore.update(person, ops);
        Person person1 = datastore.find(Person.class).get();
        System.out.println(person1);
    }
    public static void delete(){
        Datastore datastore = morphia.createDatastore(new MongoClient("localhost", 27017), "testdb");
        Person person = datastore.find(Person.class).get();
        //UpdateOperations<Person> ops = datastore.createUpdateOperations(Person.class).inc("age",100);
        datastore.delete(person);
        Person person1 = datastore.find(Person.class).get();
        System.out.println(person1);
    }




}
